#include "customparser.h"
#include "../httphandler.h"
#include "parserobserver.h"
//#include "parserglobals.h"
#include <QHttpRequestHeader>
#include <QDebug>

extern bool rapidshareLink( const QString& desc, QString& result );
extern bool uploadJockey( const QString& desc, QString& result );
extern bool parseUploadjockeyResult( const QString& desc, QString& result);

CustomParser::CustomParser( const QUrl& url, ParserObserver* observer, QObject* parent )
							:QObject(parent)
							, m_observer(observer)
							, m_done( false )
{
	//TODO:set some flag depend of url ?
	Q_ASSERT( m_observer );

	m_http = new HttpHandler( *this, this );
	m_httpHeader = NULL;

	setHeader( url );
	m_http->setHost(  url.host() );
	m_http->request( *m_httpHeader );
}

CustomParser::~CustomParser()
{
	delete m_http;
	delete m_httpHeader;
}

void CustomParser::handleResponse( QByteArray data )
{
	m_response  += data;
}

void CustomParser::error( int errCode ) 
{
	emit( parseErr( errCode, this ));
}

void CustomParser::requestFinished( bool error )
{
	if( error )
		emit( parseErr( error, this ));
}

void CustomParser::httpDone()
{
	//when transaction is done we can start parsing then notify observer and prepare for die :((
	//Set proper state parsing to avoid self loop
	QString res;
	if( rapidshareLink( m_response, res ))
	{
		emit( linkParsed( res, this ));
	}
	else if( parseUploadjockeyResult( m_response, res ))
	{
		//qDebug() << res;
		delete m_http;
		m_http = new HttpHandler( *this, this );
		QUrl url( res );
		setHeader( url );
		//qDebug() << url.toString();
		QString tmp = url.toString();
		tmp = tmp.right(tmp.length() - url.host().length() - tmp.indexOf( url.host( )) );
		m_httpHeader->setRequest("GET", tmp );
		//qDebug() << tmp;
		//m_httpHeader->setValue("Referer", url.toString());
		if( !m_cookie.isEmpty() )
		{
			//qDebug() << m_cookie;
			m_cookie+=" ao_s=1";
			m_httpHeader->setValue("Cookie", m_cookie);
			m_httpHeader->setValue("Cookie2", "$Version=1");
			
			m_http->setHost(  url.host() );
			m_http->request( *m_httpHeader );
		}
		else
			emit( parseErr( -1, this ));
	}
	//TODO:if rapidshare link not found parse some url and trigger one http object with get method
}

void CustomParser::progress( int done, int total )
{
	if( total != 0 )
		emit( progress ( (done * 100) / total ));
}

//todo: move this method to the httpHandler class
void CustomParser::setHeader( const QUrl& url )
{
	delete m_httpHeader;
	m_httpHeader = new QHttpRequestHeader( );
	m_httpHeader->setRequest("GET", url.path() );
	m_httpHeader->setValue("Host",  url.host() );
	m_httpHeader->setValue("Connection", "Keep-Alive");
	m_httpHeader->setValue("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; ru) Opera 8.50");
	
}

void CustomParser::httpResponseHeaderReceived( const QHttpResponseHeader & resp )
{
	//todo: get cookie from response: PHPSESSID
	m_cookie = resp.value("Set-Cookie");
	m_cookie = m_cookie.left( m_cookie.indexOf(" ") );

}
//eof
